//
//  JHJSongsViewController.m
//  DayByDay
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "JHJSongsViewController.h"
#import <AFNetworking.h>
#import "CellModel.h"
#import "JHJSongsCell.h"
#import "MJRefresh.h"
#import "STKAudioPlayerHandle.h"
#import "JHJTabBarController.h"

@interface JHJSongsViewController ()<UITableViewDataSource, UITableViewDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, assign)BOOL smallscrollEnable;
@property (nonatomic, strong)CellModel *cellModel;
@property (nonatomic, assign)BOOL bigScrollEnable;
@property (nonatomic, strong)NSMutableArray *array;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, assign)CGPoint point;
@property (nonatomic, assign)NSInteger row;
@property (nonatomic, assign)NSInteger lastRow;
@property (nonatomic, assign)BOOL isClickCell;
@property (nonatomic, strong)JHJTabBarController *tabBar;
@property (nonatomic, assign)CGFloat currentOffset_y;


@end

@implementation JHJSongsViewController

+(void)load
{
    NSLog(@"---666666666666666666666");

    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"666666666666666666666");
//    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
//    [stk addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
//    NSLog(@"666666666666666666666");

}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    [stk addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
    NSLog(@"dsfsd");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"sajkdfdklsfjkdsf----------------------");
    
    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    [stk removeObserver:self forKeyPath:@"currentOfMusic"];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"111");
//    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
//    [stk removeObserver:self forKeyPath:@"currentOfMusic"];
    

}

//- (void)dealloc {
//    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
//    [stk removeObserver:self forKeyPath:@"currentOfMusic"];
//}



- (void)dealloc {
    
    NSLog(@"sdsfds11212213132131313123");
    
    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    [stk removeObserver:self forKeyPath:@"currentOfMusic"];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"deliverValue" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"firstScrollEnable" object:nil];
    
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MVValue" object:nil];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"111111");
    // Do any additional setup after loading the view.
    self.array = [NSMutableArray array];
    self.page = 1;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeValue11:) name:@"deliverValue" object:nil];
//    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
//    [stk addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
//    [self createData];
    AppDelegate *tempApp = [[UIApplication sharedApplication] delegate];
    self.tabBar = tempApp.JHJTabBar;
    self.row = -1;
    NSLog(@"kdksfsdf");
    [self createView];
    [self createFooter];
    self.currentOffset_y = 0;
//    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
//    [stk addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
    
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentOfMusic"]) {
//        NSLog(@"%ld",self.isClickCell);
        NSLog(@"%@",[change valueForKey:@"new"]);
            self.lastRow = self.row;
            JHJSongsCell *lastCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:self.lastRow inSection:0]];
            lastCell.playImageView.image = [UIImage imageNamed:@"cm2_discover_icn_mv"];
            self.row = [[change valueForKey:@"new"] integerValue];
            JHJSongsCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:self.row inSection:0]];
            cell.playImageView.image = [UIImage imageNamed:@"cm2_discover_icn_music-1"];
        
        UIImageView *image = [self.view viewWithTag:80000];
        CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForItem:self.row inSection:0]];
        CGRect rectInSuperview = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
        image.frame = CGRectMake(WIDTH - 60, rectInSuperview.origin.y + 20, 25, 25);
        [self AnimationWithImageV:image];
        }
}



- (void)changeValue11:(NSNotification *)noti {
    self.value = [noti object];
//    self.array = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"deliverValue1" object:self.value];
    self.array = [NSMutableArray array];
    NSLog(@"hlskf");
    [self createData];
   
}

- (void)createFooter {
    JHJSongsViewController *songVC = self;
    NSLog(@"%ld",(long)songVC.page);
    [self.tableView addFooterWithCallback:^{
        songVC.page++;
        [songVC createData];
//     [[NSNotificationCenter defaultCenter] postNotificationName:@"songs" object:self.array];
    }];
}

- (void)createData {
    NSLog(@"111");
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *firstStr = @"http://api.dongting.com/song/singer/";
//    NSString *lastStr = @"/songs?page=1&size=50&app=ttpod&v=v9.0.1.2016050614&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.3.1&active=1&net=2&openudid=5e6106cc8d5bcf35f60a2997c79a00bb5a7c631f&idfa=ABDADD65-0877-4840-B14F-DFC8D1114AB0&utdid=VzR0dwnWYs8DANbYJ8SsFzOU&alf=(null)&bundle_id=com.ttpod.music&latitude=-1&longtitude=-1&access_token=(null)&vc=9000100";
    NSString *otherStr = @"&size=50&app=ttpod&v=v9.0.1.2016050614&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.3.1&active=1&net=2&openudid=5e6106cc8d5bcf35f60a2997c79a00bb5a7c631f&idfa=ABDADD65-0877-4840-B14F-DFC8D1114AB0&utdid=VzR0dwnWYs8DANbYJ8SsFzOU&alf=(null)&bundle_id=com.ttpod.music&latitude=-1&longtitude=-1&access_token=(null)&vc=9000100";
    NSLog(@"%ld",self.page);
    NSString *URLStr = [NSString stringWithFormat:@"%@%@/songs?page=%ld%@",firstStr,self.value,self.page,otherStr];
    NSLog(@"%@",URLStr);
    NSLog(@"%@",self.value);
    [manager GET:URLStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        self.cellModel = [CellModel new];
//        [self.cellModel setValuesForKeysWithDictionary:responseObject];
        for (NSDictionary *dic in [responseObject valueForKey:@"data"]) {
            CellSongsModel *model = [CellSongsModel new];
            [model setValuesForKeysWithDictionary:dic];
            [_array addObject:model];
        }
//        NSLog(@"%@",self.cellModel.data);
        [_tableView footerEndRefreshing];
        [_tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"songs" object:_array];
        NSLog(@"skdfkjsdlf");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
   
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playMusic" object:indexPath];
    //通知中心JHJTabBarControllerCell;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rotationImage" object:nil];
    self.isClickCell = YES;
    
    NSLog(@"===%d",self.isClickCell);
    JHJSongsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    UIImageView *image = [self.view viewWithTag:80000];
//    image.hidden = NO;
//    image.frame = CGRectMake(WIDTH - 50, 100, 25, 25);
//    image.center = CGPointMake(WIDTH - 50, cell.center.y);
//    image.size = CGSizeMake(25, 25);
    UIImageView *image = [self.view viewWithTag:80000];
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
    image.frame = CGRectMake(WIDTH - 60, rectInSuperview.origin.y + 20, 25, 25);
    [self AnimationWithImageV:image];
    NSLog(@"%f",rectInSuperview.origin.y);
//    image.center = CGPointMake(WIDTH -50, rectInSuperview.origin.y + 12.5);
    
//    NSLog(@"%f",cell.frame.size.height);
//    NSLog(@"%f",cell.frame.origin.x);
//    NSLog(@"%f",cell.frame.origin.y);
//    NSLog(@"%f",[tableView rectForRowAtIndexPath:indexPath].origin.y);

}

- (void)AnimationWithImageV:(UIImageView *)imageV {
    CAKeyframeAnimation *keyAnima=[CAKeyframeAnimation animation];
         //平移
         keyAnima.keyPath=@"position";
        //1.1告诉系统要执行什么动画
//        NSValue *value1=[NSValue valueWithCGPoint:CGPointMake(imageV.origin.x, imageV.origin.y)];
//        NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(imageV.origin.x - 200, (HEIGHT - imageV.origin.y) / 3)];
//         NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(imageV.origin.x - 250, (HEIGHT - imageV.origin.y) / 3 * 2)];
//         NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(-400 + imageV.origin.x, (HEIGHT - 100))];
//         keyAnima.values=@[value1,value2,value3,value4];
    //设置动画经过的曲线;
        CGMutablePathRef path = CGPathCreateMutable();
    //设置移动的起始点的坐标
    CGPathMoveToPoint(path, NULL, imageV.origin.x, imageV.origin.y);
    //设置中心点经过的曲线轨迹
    CGPathAddCurveToPoint(path, NULL, 300, (imageV.origin.y + HEIGHT -100) / 2, 200, (imageV.origin.y + HEIGHT -100) / 3 * 2, 50, HEIGHT - 150);
         //1.2设置动画执行完毕后，不删除动画
//         keyAnima.removedOnCompletion=NO;
         //1.3设置保存动画的最新状态
//         keyAnima.fillMode=kCAFillModeForwards;
         //1.4设置动画执行的时间
    [keyAnima setPath:path];
         keyAnima.duration=4.0;
         //1.5设置动画的节奏
         keyAnima.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [imageV.layer addAnimation:keyAnima forKey:@""];
    imageV.frame = CGRectMake(0, -500, 40, 40);
//    imageV.hidden = YES;
}

- (void)createView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT- 64 - 40) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[JHJSongsCell class] forCellReuseIdentifier:NSStringFromClass([JHJSongsCell class])];
    [self.view addSubview:self.tableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollEnable:) name:@"firstScrollEnable" object:nil];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    self.tableView.backgroundView = imageView;
    imageView.image = [UIImage imageNamed:@"1-140F6215548"];
//    [self addObserver:self forKeyPath:@"smallscrollEnable" options:NSKeyValueChangeNewKey || NSKeyValueChangeOldKey context:nil];
    self.tableView.showsVerticalScrollIndicator = NO;
//    [self.tableView addObserver:self forKeyPath:@"frame" options:NSKeyValueChangeNewKey context:nil];
    [self createImageView];

}

- (void)createImageView {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -500, 40, 40)];
    [self.view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"cm2_discover_icn_music-1"];
    imageView.tag = 80000;
//    imageView.hidden = YES;
    
}

- (void)changeScrollEnable:(NSNotification *)noti {
    self.bigScrollEnable = [[noti object] boolValue];
    self.smallscrollEnable = ![[noti object] boolValue];
//    NSLog(@"111");
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JHJSongsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JHJSongsCell class])];
    if (indexPath.row == self.row) {
        cell.isClick = YES;
    } else {
        cell.isClick = NO;
    }
    cell.model = self.array[indexPath.row];
    cell.numberLabel.text  = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    cell.selectionStyle = 0;
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.bigScrollEnable) {
        self.smallscrollEnable = !self.bigScrollEnable;
    }
    if (!self.smallscrollEnable && scrollView.contentOffset.y >= 0) {
        scrollView.contentOffset = self.point;
        
    } else if (scrollView.contentOffset.y <= 0) {
        if (self.smallscrollEnable) {
            self.smallscrollEnable = NO;
            
        }
        self.point = CGPointZero;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"bingScrollEnable" object:[NSNumber numberWithBool:self.smallscrollEnable]];
        
    }
    if ( scrollView.contentOffset.y > 0) {
        self.point = scrollView.contentOffset;
    }
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointZero;
    }
    if(scrollView.contentOffset.y > 0 && self.bigScrollEnable == YES) {
        self.smallscrollEnable = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"bingScrollEnable" object:[NSNumber numberWithBool:self.smallscrollEnable]];
    }
    
    if (self.currentOffset_y < scrollView.contentOffset.y) {
        [self.tabBar hiddenTabBarWithAnimation:YES];
    } else {
        [self.tabBar showTabBarWithAnimation:YES];
    }
    self.currentOffset_y = scrollView.contentOffset.y;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
